/* 
Promise.race是类上的方法，类上的方法是静态方法，可以实现只要有一个执行完就返回结果;
*/

const Promise = require("./then");

let fs = require("fs");
let path = require('path');

function read(url){
    let dfd = Promise.defer();

    let pathUrl = path.resolve(__dirname,url);
    
    fs.readFile(pathUrl,'utf8',function(err, data){
        if(err) dfd.reject(err);
        dfd.resolve(data);
    });

    return dfd.promise;
}

read('./txt/a.txt').then(res => {
    console.log(res);
},err => {
    console.log(err);
});

function isPromise(x){
    if(typeof x === "object" && x!==null || typeof x === "function"){
        if(typeof x.then === "function"){
            return true;
        }
    }else{
        return false;
    }
}

Promise.race = function(values){
    return new Promise((resolve,reject) => {
        for(let i=0;i<values.length;i++){
            let current = values[i];
            if(isPromise(values[i])){
                current.then(data => {
                    resolve(data);
                    return;
                },reject);
            }else{
                resolve(current);
                return;
            }
        }
    });
}

//只要有一个成功就返回结果
Promise.race([
    read('../txt/a.txt'),
    read('../txt/b.txt'),
    read('../txt/c.txt'),
    read('../txt/d.txt')
]).then(data => {
    //这里返回的是首先成功的promise结果
    console.log(data);
},err => {
    console.log(err);
});